package isp.apps.example.shoppingadmin.action;

import com.opensymphony.xwork.ActionSupport;

import isp.apps.example.shoppingcart.domain.Item;
import isp.apps.example.shoppingcart.domain.ShoppingCartValidator;
import isp.apps.example.shoppingcart.persistence.ItemDirectory;
import isp.apps.example.shoppingcart.persistence.ItemRepository;
import isp.apps.example.shoppingcart.persistence.factory.ItemPersistenceFactory;

import java.math.BigDecimal;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class UpdateItemsAction
  extends ActionSupport
{
  private Map itemNameMap;
  private Map itemCostMap;
  private Map itemDescriptionMap;
  private Map itemInventoryMap;
  private Map itemValidMap;
  private List items;

  public UpdateItemsAction()
  {
  }

  public void setItems(List pItems)
  {
    items = pItems;
  }

  public List getItems()
  {
    return items;
  }


  public String execute()
  {
    validate();
    if (hasActionErrors())
      return SUCCESS;
    writeToRepository();
    return SUCCESS;
  }

  public void writeToRepository()
  {
    //comments below are for comparing the newItem values to the existing item values
    //and eliminating a redundant write to the repository if the item has not changed

    //Item newItem = new Item();
    ItemRepository ir = ItemPersistenceFactory.getItemRepository();
    for (Iterator i = items.iterator(); i.hasNext(); )
    {
      
      Item item = (Item) i.next();
      String id = item.getId().toString();
      
      //set on newItem instead

       //if old valid is 1 & newValid is 0 then set invalidDate stamp
        if ((item.getValid().intValue() == 1) && 
            ((new Integer((String)itemValidMap.get(id))).intValue() == 0)
            )
        {
          Calendar today = new GregorianCalendar();
          today.setTime(new Date());
          item.setInvalidDate(today);
        }
        
      item.setValid(new Integer((String)itemValidMap.get(id)));
      item.setName((String) itemNameMap.get(id));
      item.setDescription((String) itemDescriptionMap.get(id));
      item.setCost(new BigDecimal((String) itemCostMap.get(id)));
      item.setInventory(new Integer((String)itemInventoryMap.get(id)));
      
      //if (item.compareTo(newItem))
        //ir.saveItem(newItem);
      //if item was valid and is now being set to invlaid
      //get current time and set it
      
      //if NOT equal.....
      ir.saveItem(item);
    }
  }

  public void validate()
  {

    ShoppingCartValidator scv = new ShoppingCartValidator();

    for (Iterator i = items.iterator(); i.hasNext(); )
    {
      Item item = (Item) i.next();
      String id = item.getId().toString();
      String name, desc, cost, valid, inventory;

      if (!(itemNameMap.containsKey(id) &&
            itemDescriptionMap.containsKey(id) &&
            itemCostMap.containsKey(id) && itemValidMap.containsKey(id) &&
            itemInventoryMap.containsKey(id)))
      {
        addActionError("Invalid POST method or missing / corrupted items list.");
        return;
      }

      name = (String) itemNameMap.get(id);
      desc = (String) itemDescriptionMap.get(id);
      cost = (String) itemCostMap.get(id);
      valid = (String) itemValidMap.get(id);
      inventory = (String) itemInventoryMap.get(id);

      if ((name = scv.checkText(name)) == null)
      {
        addActionError("Please specify a valid name for the new item: " +
                       name + "\"");
        return;
      }
      //item.setName(name);

      if ((desc = scv.checkText(desc)) == null)
      {
        addActionError("Please specify a valid description for the new item: " +
                       name + "\"");
        return;
      }
      //item.setDescription(desc);

      if ((cost = scv.checkCurrency(cost)) == null)
      {
        addActionError("Please specify a valid cost for the new item (1-7 digits, optionally 2 decimal places): " +
                       name + "\"");
        return;
      }
      //item.setCost(new BigDecimal(cost));

      if ((valid = scv.checkBoolean(valid)) == null)
      {
        addActionError("Please specify a valid cost for the new item (1-7 digits, optionally 2 decimal places): " +
                       name + "\"");
        return;
      }
      //item.setValid(new Integer(valid));

      if ((inventory = scv.checkNumber(inventory)) == null)
      {
        addActionError("Please specify a valid inventory for the new item: " +
                       name + "\"");
        return;
      }
      //item.setInventory(new Integer(inventory));

      itemNameMap.put(id, name);
      itemDescriptionMap.put(id, desc);
      itemCostMap.put(id, cost);
      itemValidMap.put(id, valid);
      itemInventoryMap.put(id, inventory);
    }
    //END iterator for items list from Persistence
  }
  // END validate


  public Map getItemNameMap()
  {
    if (itemNameMap == null)
      itemNameMap = new HashMap();
    return itemNameMap;
  }

  public Map getItemDescriptionMap()
  {
    if (itemDescriptionMap == null)
      itemDescriptionMap = new HashMap();
    return itemDescriptionMap;
  }

  public Map getItemCostMap()
  {
    if (itemCostMap == null)
      itemCostMap = new HashMap();
    return itemCostMap;
  }

  public Map getItemInventoryMap()
  {
    if (itemInventoryMap == null)
      itemInventoryMap = new HashMap();
    return itemInventoryMap;
  }

  public Map getItemValidMap()
  {
    if (itemValidMap == null)
      itemValidMap = new HashMap();
    return itemValidMap;
  }
}
